package com.cristina.attention.event;

import com.alibaba.fastjson.JSON;
import com.cristina.attention.domain.MessageInfo;
import com.cristina.attention.domain.TaskInfo;
import com.cristina.attention.utils.AttentionCommon;
import com.cristina.attention.utils.enums.ChannelType;
import com.cristina.attention.utils.enums.MessageType;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author by superman
 */
@AllArgsConstructor
@NoArgsConstructor
public class SyncChatListener {

    @Resource
    private KafkaTemplate<String, Object> kafkaTemplate;

    @Value("${attention.topic.name}")
    private String topicName;

    @Async
    @Order
    @EventListener(SyncChatEvent.class)
    public void event(SyncChatEvent event) {
        Object syncChats = event.getSource();
        MessageInfo messageInfo = MessageInfo.builder()
                .messageId(null)
                .businessId(null)
                .msgType(MessageType.SYNC.getCode())
                .msgContext(JSON.toJSONString(syncChats))
                .sendChannel(ChannelType.IM_CHAT.getCode())
                .build();

        List<MessageInfo> messageInfoList = new ArrayList<>();
        messageInfoList.add(messageInfo);
        TaskInfo taskInfo = new TaskInfo(AttentionCommon.TRUE);
        taskInfo.setMessageInfos(messageInfoList);
        kafkaTemplate.send(topicName, JSON.toJSONString(taskInfo));
    }
}
